import axios from 'axios'
import {Loading,Message} from 'element-ui'
import router from '@/router/index.js'

const request = axios.create({
    baseURL:'http://localhost:8088/member/',
    timeout:5000
})


//响应拦截器
request.interceptors.response.use(response => {
    loading.close();
    const resp = response.data
    if(resp.code != 2000){
        Message({
                message:resp.msg || '系统异常',
                type:'warning',
                duration: 2 * 1000
            })

            if(resp.code == 401){
                router.push("/login");
            }

            return Promise.reject();
    }
    return response.data
},error => {
    loading.close();
    var msg = '';
    // if(error.response.status == 404){
    //         msg = '服务器离家出走了—~~~~~~'
    // }
    Message({
        msg:msg || error.msg,
        type:'error',
        duration: 1500
    })
    return Promise.reject(error);
})

//请求拦截器
request.interceptors.request.use(config => {
    loading.open();
    const token = localStorage.getItem('wanshi-mms-token')
    if(token){
        config.headers.Authorization = `Bearer ${token}`
    }
    return config;
},error =>{
    loading.close();
    return  Promise.reject(error);
})


const loading = {
    loadingInstance : null,
    open: function(){
        if(this.loadingInstance == null){
            this.loadingInstance = Loading.service({
                target:'.main',
                text:'拼命加载中...',
                background:'rgba(0,0,0,0.5)'
            })
        }
    },
    close: function(){
        if(this.loadingInstance !==null){
            this.loadingInstance.close()
        }
        this.loadingInstance = null
    }
}


export default request;